/**   
* @Title: OrderByProvinceImpl.java 
* @Package com.lvmama.rhino.service.impl 
* @Description: TODO
* @author Administrator
* @date 2016年9月26日 下午12:49:40 
* @version V1.0   
*/
package com.lvmama.rhino.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lvmama.rhino.entity.AliReturn;
import com.lvmama.rhino.entity.BaiduIp;
import com.lvmama.rhino.entity.OrderCount;
import com.lvmama.rhino.entity.TaoIp;
import com.lvmama.rhino.mapperHippo.OrderByProvinceMapper;
import com.lvmama.rhino.pojo.OrderLogData;
import com.lvmama.rhino.service.OrderByProvinceService;

/** 
 * @ClassName: OrderByProvinceImpl 
 * @Description: TODO
 * @author Administrator
 * @date 2016年9月26日 下午12:49:40  
 */
@Service
public class OrderByProvinceImpl implements OrderByProvinceService {

	private final Logger logger=Logger.getLogger(this.getClass());
	@Autowired
    private CloseableHttpClient httpClient;
	@Autowired
    private RequestConfig requestConfig;
	private static final ObjectMapper MAPPER = new ObjectMapper();
	@Autowired
	private OrderByProvinceMapper orderByProvinceMapper;
	
	private static final String BAIDUKEY="vXcAWKiXGvl61v0oyly4GRjFQZ3wnA9g";
	@Override
	public List<OrderCount> queryOrderByProvince() {
		List<OrderLogData> orderList=orderByProvinceMapper.queryOrderByProvince();
		logger.info("查询出："+orderList.size());
		Properties properties=new Properties();
		try {
			properties.load(this.getClass().getClassLoader().getResourceAsStream("/province.properties"));
		} catch (IOException e) {
			e.printStackTrace();
			logger.info("加载省份配置文件失败");
		}
		Map<String,String> map=new HashMap<String,String>((Map)properties);
		for (OrderLogData orderLogData : orderList) {
			if(orderLogData==null){
				continue;
			}
			logger.info("订单数据："+orderLogData.toString());
			String queryProvince=orderLogData.getProvince();
			if(StringUtils.isBlank(queryProvince)){
				String globalLatitude = orderLogData.getGlobalLatitude();
				String globalLongitude = orderLogData.getGlobalLongitude();
				String ip = orderLogData.getIp();
				if(StringUtils.isNotBlank(globalLatitude) && StringUtils.isNotBlank(globalLongitude)){
				queryProvince = queryProvince(globalLongitude, globalLatitude);
				}else if(StringUtils.isNotBlank(ip)){
					queryProvince=queryProvinceByIP(ip);
				}
			}
			
			if(StringUtils.isNotBlank(queryProvince)){
				for(String key:map.keySet()){
					if(queryProvince.contains(key)){
						Integer value = Integer.valueOf(map.get(key));
						value=value+1;
						map.put(key, value.toString());
				}
				}
			}
		}
		List<OrderCount> list=new ArrayList<>();
		for(String key:map.keySet()){
			OrderCount orderCount=new OrderCount();
			orderCount.setName(key);
			orderCount.setValue(map.get(key));
			list.add(orderCount);
		}
		
		return list;
	}
	
	public String queryProvince(String longitude,String latitude){
		String url="http://recode.ditu.aliyun.com/dist_query?l="+latitude+","+longitude;
		HttpGet httpGet=new HttpGet(url);
		httpGet.setConfig(requestConfig);
		CloseableHttpResponse response=null;
		try {
			response=httpClient.execute(httpGet);
			if (response.getStatusLine().getStatusCode() == 200) {
	            String json= EntityUtils.toString(response.getEntity(),"GBK");
	            AliReturn aliProvince = MAPPER.readValue(json, AliReturn.class);
	            String dist = aliProvince.getDist();
	            String[] split = dist.split(",");
	            if(split!=null && split.length>1){
		            return split[1];
		            }
		        else{
		        		logger.info("经纬度定位省份失败:"+longitude+","+latitude);
		            	return null;
		            }
	        }
		} catch (Exception e) {
			logger.info("调取阿里接口失败:"+longitude+","+latitude);
			e.printStackTrace();
		}
		
		return null;
	}
	
	/**
	 * 
	* @Title: queryProvinceByIP 
	* @Description: 调用百度接口通过ip定位省份
	* @param @param ip
	* @param @return    设定文件 
	* @return String    返回类型 
	* @throws
	 */
	public String queryProvinceByIP(String ip){
		String url="http://api.map.baidu.com/location/ip?coor=bd09ll&ak=" + BAIDUKEY + "&ip=" + ip;
		HttpGet httpGet=new HttpGet(url);
		httpGet.setConfig(requestConfig);
		CloseableHttpResponse response=null;
		try {
			response=httpClient.execute(httpGet);
			if (response.getStatusLine().getStatusCode() == 200) {
	            String json= EntityUtils.toString(response.getEntity(),"UTF-8");
	            BaiduIp baiduIp = MAPPER.readValue(json, BaiduIp.class);
	            if(baiduIp!=null && "0".equals(baiduIp.getStatus())){
	            	if(baiduIp.getContent() !=null && baiduIp.getContent().getAddress_detail()!=null){
	            		return baiduIp.getContent().getAddress_detail().getProvince();
	            	}
	            }
	        }
		} catch (Exception e) {
			logger.info("调用百度接口定位省份失败："+ip);
		}
		
		return null;
	}
}
